/**
 * Created by user on 2015/10/14.
 */

var async = require('async');
var mysqlUtil = require('../../../common/utils/mysqlUtil');
var H5 = mongoose.model('masterData_h5');

exports.h5ListService = function(req ,callback) {

    var body = req.body;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var paged = (req.params.size && req.params.page);

    var option = body;
    //var sortType = paged ? {endDate:-1} : {};

    if (option.name) option.name = new RegExp(option.name);
    if (option.desc) option.desc = new RegExp(option.desc);

    logger.debug(option);
    async.series([

        function (callbackInner) {
            H5.count(option, function (err, count) {

                if (err) {
                    callbackInner(err, null);
                }else {
                    var temp = {count: count, totalPage:Math.ceil(count/size)};
                    callbackInner(err, temp);
                }
            });
        },
        function (callbackInner) {

            H5.find(option).sort({dateCreated:-1}).skip(index).limit(size).exec(function (err, results) {

                    if (err) {
                        callbackInner(err);
                    } else {
                        callbackInner(null, results);
                    }
                });

        }], callback);

};


exports.h5AddService = function(req ,callback) {

    var body = req.body;
    //logger.debug(body);
    var data = {
        name : body.name
        ,desc : body.desc
        ,url: body.url
    };

    logger.debug(data);

    var temp = new H5(data);
    temp.save(callback);


};

exports.h5DeleteService = function (req, callback) {

    var ids = req.body.id;

    var h5In = {};
    h5In["$in"] = [];
    for (var i = 0, l = ids.length; i < l; i++) {
        h5In["$in"].push(ids[i]);
    }
    logger.debug(h5In);
    H5.remove({_id :h5In}, callback);
};


exports.h5EditService = function(req ,callback) {

    var body = req.body;

    logger.debug(body);

    H5.update({_id: body.id}, body.h5, callback);
};

